package com.ad.nbi.epirpsystem.server;

import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import org.omg.CosNaming.NamingContextExt;
import org.omg.CosNaming.NamingContextExtHelper;
import org.omg.PortableServer.Servant;

import com.ad.nbi.FileTransferIRPSystem.FileTransferIRPServerImpl;
import com.ad.nbi.NotificationIRP.NotificationIRPServerImpl;

public class Server extends Thread{
	public static final String IOR_BASE_PATH = "E:/NBI/iors/";
	public static final String CSIRP_IOR = "CSIRP_IOR";
	public static final String EPIRP_IOR = "EPIRP_IOR";
	public static final String FILE_TRANSFER_IOR = "FILE_TRANSFER_IOR";
	public static final String NTFY_SERVER_IOR = "NTFY_SERVER_IOR";
	
	public static Map<String, String> iors = new HashMap<String, String>();
	private org.omg.CORBA.ORB orb;

	public Server(String[] args, Servant interfImpl, String iorkey) {
		orb = org.omg.CORBA.ORB.init(args, null);

		try

		{

			org.omg.PortableServer.POA poa =

			org.omg.PortableServer.POAHelper.narrow(

			orb.resolve_initial_references("RootPOA"));

			poa.the_POAManager().activate();

			org.omg.CORBA.Object o = poa.servant_to_reference(interfImpl);

			if (args.length == 1)

			{
				PrintWriter ps = new PrintWriter(

				new FileOutputStream(

				new File(args[0])));
				String IOR = orb.object_to_string(o);
				ps.println(IOR);
				ps.close();
				iors.put(iorkey, IOR);
			}

			else

			{

				// register with the naming service

				NamingContextExt nc =

				NamingContextExtHelper.narrow(

				orb.resolve_initial_references("NameService"));

				nc.bind(nc.to_name("grid.example"), o);

			}

		}

		catch (Exception e)

		{

			e.printStackTrace();

		}

	}

	@Override
	public void run() {
		orb.run();

	}

	public static void main(String[] args)

	{
		
		new Server(new String[] { IOR_BASE_PATH + EPIRP_IOR },new EPIRPServerImpl(iors), "EPIRPServerImpl").start();
		
		new Server(new String[] { IOR_BASE_PATH + CSIRP_IOR },new CSIRPServerImpl(), EPIRPServerImpl.IOR_KEY_CSIRP).start();
		
		new Server(new String[] { IOR_BASE_PATH + FILE_TRANSFER_IOR },new FileTransferIRPServerImpl(), "FileTransferIRPServerImpl").start();
		
		new NtfyServer(new String[] { IOR_BASE_PATH + NTFY_SERVER_IOR },new NotificationIRPServerImpl(), "NotificationIRPServerImpl").start();
		
		System.out.println("start success!");
	}
	
}